<template>
  <div :id="name" class="chart-container"></div>
</template>
<script>
import { Line } from '@antv/g2plot'
export default {
  data () {
    return {
      line: null,
    }
  },
  props: {
    name: {
      type: String,
      default: 'LineCanvas'
    },
    data: {
      type: Array,
      default: () => []
    },
    unit: {
      type: String,
      default: ' 元'
    }
  },
  mounted() {
    this.line = new Line(this.name, {
      data: this.data,
      xField: 'x',
      yField: 'y',
      seriesField: 'type',
      yAxis: {
        grid: {
          line: {
            style: {
              stroke: 'white',
              lineWidth: 1,
              lineDash: [4, 4],
              opacity: 0.2,
              cursor: 'pointer'
            }
          }
        },
        label: {
          // 数值格式化为千分位
          formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
        },
      },
      smooth: true,
      color: ['#019cf6', '#fb7293', '#52C41A', '#FFA940'],
      tooltip: {
        formatter: (datum) => {
          return { name: datum.type, value: this.thousands(datum.y) + this.unit };
        }
      }
    })
    this.line.render()
  },
  methods: {
    thousands: function (num) {
      var str = num.toString();
      var reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
      return str.replace(reg,"$1,");
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
